#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import sys

# 基础URL
BASE_URL = "http://localhost:5000"

# 颜色定义
COLORS = {
    "GREEN": "\033[92m",
    "YELLOW": "\033[93m",
    "RED": "\033[91m",
    "BLUE": "\033[94m",
    "ENDC": "\033[0m"
}

def print_color(text, color):
    print(f"{COLORS[color]}{text}{COLORS['ENDC']}")

def login(username, password):
    """登录并获取认证令牌"""
    login_url = f"{BASE_URL}/api/auth/login"
    login_data = {"username": username, "password": password}
    
    try:
        response = requests.post(login_url, json=login_data)
        if response.status_code == 200:
            token = response.json().get("access_token")
            print_color(f"✓ 登录成功: {username}", "GREEN")
            return token
        else:
            print_color(f"✗ 登录失败: {response.text}", "RED")
            return None
    except Exception as e:
        print_color(f"✗ 登录请求异常: {str(e)}", "RED")
        return None

def get_user_info(token):
    """获取当前用户信息"""
    user_url = f"{BASE_URL}/api/auth/profile"
    headers = {"Authorization": f"Bearer {token}"}
    
    try:
        response = requests.get(user_url, headers=headers)
        if response.status_code == 200:
            user_info = response.json().get("user")
            print_color(f"✓ 获取用户信息成功: {user_info['username']} (角色: {user_info['role']})", "GREEN")
            if user_info.get('area_id'):
                print_color(f"  - 主区域ID: {user_info['area_id']}", "BLUE")
            if user_info.get('area_name'):
                print_color(f"  - 主区域名称: {user_info['area_name']}", "BLUE")
            return user_info
        else:
            print_color(f"✗ 获取用户信息失败: {response.text}", "RED")
            return None
    except Exception as e:
        print_color(f"✗ 获取用户信息请求异常: {str(e)}", "RED")
        return None

def get_work_orders(token, status, area_filter=True):
    """获取工单列表"""
    orders_url = f"{BASE_URL}/api/work_orders"
    headers = {"Authorization": f"Bearer {token}"}
    params = {
        "per_page": 100,
        "status": status,
        "area_filter": "true" if area_filter else "false"
    }
    
    try:
        response = requests.get(orders_url, headers=headers, params=params)
        if response.status_code == 200:
            data = response.json()
            work_orders = data.get("work_orders", [])
            pagination = data.get("pagination", {})
            total = pagination.get("total", 0)
            
            print_color(f"✓ 获取{status}工单成功: 共{total}个", "GREEN")
            
            # 打印工单信息
            if work_orders:
                print_color("  工单列表:", "BLUE")
                for i, order in enumerate(work_orders[:5], 1):  # 只显示前5个
                    title = order.get("title", "无标题")
                    order_id = order.get("id")
                    area_name = order.get("area", {}).get("name", "无区域")
                    assignee = order.get("assignee", {}).get("name", "无负责人")
                    print_color(f"  {i}. [{order_id}] {title} (区域: {area_name}, 负责人: {assignee})", "YELLOW")
                
                if len(work_orders) > 5:
                    print_color(f"  ... 还有{len(work_orders) - 5}个工单未显示", "YELLOW")
            else:
                print_color("  没有找到工单", "YELLOW")
            
            return work_orders
        else:
            print_color(f"✗ 获取工单失败: {response.text}", "RED")
            return []
    except Exception as e:
        print_color(f"✗ 获取工单请求异常: {str(e)}", "RED")
        return []

def main():
    if len(sys.argv) < 3:
        print("用法: python test-mobile-orders.py <用户名> <密码>")
        return
    
    username = sys.argv[1]
    password = sys.argv[2]
    
    print_color("===== 移动端工单获取测试 =====", "BLUE")
    
    # 登录获取令牌
    token = login(username, password)
    if not token:
        return
    
    # 获取用户信息
    user_info = get_user_info(token)
    if not user_info:
        return
    
    print_color("\n----- 测试区域过滤启用 -----", "BLUE")
    
    # 测试获取待接单工单（区域过滤启用）
    print_color("\n1. 获取待接单工单（区域过滤启用）:", "BLUE")
    pending_orders = get_work_orders(token, "pending", True)
    
    # 测试获取处理中工单（区域过滤启用）
    print_color("\n2. 获取处理中工单（区域过滤启用）:", "BLUE")
    in_progress_orders = get_work_orders(token, "in_progress", True)
    
    # 测试获取已完成工单（区域过滤启用）
    print_color("\n3. 获取已完成工单（区域过滤启用）:", "BLUE")
    completed_orders = get_work_orders(token, "completed", True)
    
    print_color("\n----- 测试区域过滤禁用 -----", "BLUE")
    
    # 测试获取待接单工单（区域过滤禁用）
    print_color("\n4. 获取待接单工单（区域过滤禁用）:", "BLUE")
    pending_orders_no_filter = get_work_orders(token, "pending", False)
    
    # 测试获取处理中工单（区域过滤禁用）
    print_color("\n5. 获取处理中工单（区域过滤禁用）:", "BLUE")
    in_progress_orders_no_filter = get_work_orders(token, "in_progress", False)
    
    # 测试获取已完成工单（区域过滤禁用）
    print_color("\n6. 获取已完成工单（区域过滤禁用）:", "BLUE")
    completed_orders_no_filter = get_work_orders(token, "completed", False)

if __name__ == "__main__":
    main()